package com.yydm.serviceacls.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yydm.commonutils.R;
import com.yydm.serviceacls.entity.Permission;
import com.yydm.serviceacls.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 * 权限管理
 */
@RestController
@RequestMapping("/acl/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionServer;


    /**
     * 权限管理+模糊查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R page(int page,int pageSize,String name){
        System.out.println(page+""+pageSize);
        Page<Permission> objectPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Permission> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name),Permission::getName,name);
        permissionServer.page(objectPage,queryWrapper);
        return R.ok().data("obj",objectPage);
    }

    /**
     * 新增权限
     * @param permission
     * @return
     */
    @PostMapping("savePermission")
    public R save(@RequestBody Permission permission){
        boolean save = permissionServer.save(permission);
        if (save){
            return R.ok().message("新增成功");
        }
        return R.error().message("新增失败");
    }

    /**
     * 更新权限
     * @param permission
     * @return
     */
    @PutMapping("updatePermission")
    public R update(@RequestBody Permission permission){
        LambdaQueryWrapper<Permission> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getId,permission.getId());
        boolean update = permissionServer.update(permission,queryWrapper);
        if (update){
            return R.ok().message("修改成功");
        }
        return R.error().message("修改失败");
    }

    /**
     * 删除权限
     * @param id
     * @return
     */
    @DeleteMapping("delPermission")
    public R delete(Long id){
        permissionServer.delete(id);
        return R.ok().message("删除成功");
    }

    /**
     * 查询全部权限
     * @return
     */
    @GetMapping("permissionList")
    @PreAuthorize("hasAuthority('/role')")
    public R list(){
        List<Permission> list = permissionServer.list();
        return R.ok().data("list",list);
    }

}
